package cn.com.nxt.txb;

import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Base64;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.Gson;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import cn.com.nxt.txb.httpdelegate.LinkDelegate;
import cn.com.nxt.txb.model.User;
import cn.com.nxt.txb.util.AppConstant;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.util.DateTimePickerDialog;
import cn.com.nxt.txb.util.LogoutHelper;

@ContentView(R.layout.activity_invite_meeting)
public class InviteMeetingActivity extends BaseActivity {
    @ViewInject(R.id.tv_time)
    private TextView mTvTime;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    private String startTime;
    private LinkDelegate linkDelegate;
    private final byte SEND_MSG_FLAG = 0x70;
    public static final byte RESULT_BUSINESS = 0x002;//选择企业通讯录时返回


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);//注解绑定
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        linkDelegate = new LinkDelegate(this);
    }

    @Event({R.id.ll_time, R.id.ll_msg, R.id.ll_copy})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.ll_time:
                selectTime();
                break;
            case R.id.ll_msg:
                sendMsg();
                break;
            case R.id.ll_copy:
                copy();
                break;
        }
    }

    private String getLink() {
        StringBuilder sb = new StringBuilder(AppUtil.mUser.getUsername() + "&" + AppUtil.mUser.getRommid());
        if (!AppUtil.isBlank(startTime)) {
            sb.append("&" + startTime.replaceAll("-", ":"));
        }
        String encodedString = Base64.encodeToString(sb.toString().getBytes(), Base64.DEFAULT);
        return AppConstant.INVITER_MEETING + "?token=" + encodedString;
    }

    private void sendMsg() {
        if (AppUtil.isBlank(startTime)) {
            showToast("请先选择开始时间");
            return;
        }
        skipBusiness();
//        final EditText inputServer = new EditText(this);
//        inputServer.setFocusable(true);
//        inputServer.setInputType(InputType.TYPE_CLASS_PHONE);
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("短信邀请").setView(inputServer).setNegativeButton("从通讯录选择", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Uri uri = Uri.parse("content://contacts/people");
//                Intent intent = new Intent(Intent.ACTION_PICK, uri);
//                startActivityForResult(intent, 0);
//            }
//        });
//        builder.setPositiveButton("确定",
//                new DialogInterface.OnClickListener() {
//
//                    public void onClick(DialogInterface dialog, int which) {
//                        String inputName = inputServer.getText().toString();
//                        if(AppUtil.isPhoneNumberValid(inputName)){
//                            sendSms(inputName);
//                        }else{
//                            showToast("电话格式不正确");
//                        }
//                    }
//                });
//        builder.show();
    }


    private void skipBusiness() {
        Intent intent = new Intent(InviteMeetingActivity.this, ChooseBusinessActivity.class);
        startActivityForResult(intent, RESULT_BUSINESS);
    }

    private void copy() {
        showToast("链接已复制");
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(getLink().trim());
    }

    private DateTimePickerDialog.OnDateSetListener mDateSetListener = new DateTimePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth, TimePicker timeview, int hourOfDay, int minut) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            mHour = hourOfDay;
            mMinute = minut;
            startTime = updateDisplay(0);
            mTvTime.setText(startTime);
        }
    };

    @Override
    protected android.app.Dialog onCreateDialog(int id) {
        return new DateTimePickerDialog(this, mDateSetListener, mYear, mMonth,
                mDay, mHour, mMinute, false);
    }


    private void selectTime() {
        showDialog(0);
    }

    private String updateDisplay(int i) {

        String timestr;
        if (i == 0) {
            timestr = new StringBuilder()
                    .append(mYear)
                    .append("-")
                    .append((mMonth + 1) < 10 ? "0" + (mMonth + 1)
                            : (mMonth + 1)).append("-")
                    .append((mDay < 10) ? "0" + mDay : mDay).append(" ")
                    .append(pad(mHour)).append(":").append(pad(mMinute))
                    .toString();
        } else {
            timestr = new StringBuilder()
                    .append(mYear)
                    .append("-")
                    .append((mMonth + 1) < 10 ? "0" + (mMonth + 1)
                            : (mMonth + 1)).append("-")
                    .append((mDay < 10) ? "0" + mDay : mDay).toString();
        }

        return timestr;
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    private void sendSms(String phone) {
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("name", AppUtil.mUser.getUsername());
        map.put("roomid", AppUtil.mUser.getRommid());
        map.put("time", startTime);
        Gson gson = new Gson();
        showDialog();
        linkDelegate.smsInviter(gson.toJson(map), SEND_MSG_FLAG);
    }

    @Override
    public void success(String result, byte flag) {
        super.success(result, flag);
        showToast("发送成功");
        disDialog();
    }

    @Override
    public void failure(String result, byte flag, ResponseStatus status) {
        super.failure(result, flag, status);
        showToast(result);
        disDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                sendSms(contacts[1]);
//                et_name.setText(contacts[0]);
//                et_tele.setText(contacts[1]);
                break;
            case RESULT_BUSINESS:
                if (requestCode == RESULT_BUSINESS) {
                    if (data == null)
                        return;
                    String phone = data.getExtras().getString("phone");//得到新Activity关闭后返回的数据
                    // showToast(phone);
                    sendSms(phone);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }
}
